/******************************************************************************
 * Product: Adempiere ERP & CRM Smart Business Solution                       *
 * This program is free software; you can redistribute it and/or modify it    *
 * under the terms version 2 of the GNU General Public License as published   *
 * by the Free Software Foundation. This program is distributed in the hope   *
 * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied *
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.           *
 * See the GNU General Public License for more details.                       *
 * You should have received a copy of the GNU General Public License along    *
 * with this program; if not, write to the Free Software Foundation, Inc.,    *
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.                     *
 * For the text or an alternative of this public license, you may reach us    *
 * Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved.               *
 * Contributor(s): Victor Perez www.e-evolution.com                           *
 *****************************************************************************/

package org.compiere.process;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.model.MBankStatementLine;
import org.compiere.model.MInOutLine;
import org.compiere.model.MInventoryLine;
import org.compiere.model.MInvoice;
import org.compiere.model.MInvoiceLine;
import org.compiere.model.MJournalLine;
import org.compiere.model.MMovement;
import org.compiere.model.MPayment;
import org.compiere.model.Mhrmvacation;
import org.compiere.model.Mhrmvacationline;
import org.compiere.util.DB;

/**
 * Production of BOMs
 *   1) Creating ProductionLines when IsCreated = 'N'
 *   2) Posting the Lines (optionally only when fully stocked)
 * 
 * @author victor.perez@e-evolution.com
 * @contributor: Carlos Ruiz (globalqss) - review backward compatibility - implement mustBeStocked properly
 */
public class FactAcctUpdate extends SvrProcess {

	/** The Record */
	private int p_Record_ID = 0;

	/**	Period Parameter				*/
	private Timestamp			p_DateAcct_From = null;
	private Timestamp			p_DateAcct_To = null;
	/**	Org Parameter					*/
	private int					p_AD_Org_ID = 0;

	private String				m_trxName = null;
	
	private Properties				m_ctx = null;
	/**
	 * Prepare - e.g., get Parameters.
	 */
	protected void prepare() {
		ProcessInfoParameter[] para = getParameter();
		for (int i = 0; i < para.length; i++) {
			String name = para[i].getParameterName();
			if (para[i].getParameter() == null)
				;
			else if (name.equals("AD_Org_ID"))
			{
				p_AD_Org_ID = para[i].getParameterAsInt();
			}	
			else if (name.equals("DateAcct"))
			{
				p_DateAcct_From = (Timestamp)para[i].getParameter();
				p_DateAcct_To = (Timestamp)para[i].getParameter_To();
			}
			else
				log.log(Level.SEVERE, "Unknown Parameter: " + name);
		}
		p_Record_ID = getRecord_ID();
		m_trxName = get_TrxName();
		m_ctx = getCtx();
		log.log(Level.INFO, "Record_ID " + p_Record_ID);
		
	} //prepare

	/**
	 * Process
	 * 
	 * @return message
	 * @throws Exception
	 */

	protected String doIt() throws Exception 
	{
		log.info("Search fields in Fact_acct");
		int iTableID, iRecordID, iLineID, iChargeID, iCounter, iAID , iAID2, iContractID, iAssetID, iProductID;
//		String clientCheck = " AND AD_Client_ID=" + getAD_Client_ID();		
		StringBuffer sql =  new StringBuffer("SELECT f.AD_Table_ID, f.Record_ID, f.Line_ID, f.C_Charge_ID, f.Counter "
			+ ", f.Account_ID AS AID, f2.Account_ID AS AID2, f.AmtAcctDr, f.AmtAcctCr, f.C_BPartner_ID, f.CMS_Contract_ID "	
			+ ", f.A_Asset_ID, f.M_Product_ID "	
    		+ " FROM Fact_Acct AS f"
			+ " LEFT JOIN  Fact_Acct AS f2 ON ( f2.ad_table_id = f.ad_table_id"
			+ " and f2.record_id = f.record_id " 
			+ " and f2.counter = f.reference)"	
    		+ " WHERE f.isActive = 'Y'"
    		+ " AND f.DateAcct >="+DB.TO_DATE(p_DateAcct_From, true)
    		+ " AND f.DateAcct <="+DB.TO_DATE(p_DateAcct_To, true)
    		+ " AND f.AD_Org_ID = "+p_AD_Org_ID
    		+ " AND f.Account_ID IN ( SELECT c_elementvalue_id from c_elementvalue "
    		+ " WHERE (value like '7%' or value like '6%' ) and ad_client_id = 1000000"
    		+ " AND issummary = 'N')"
    		+ " ORDER BY f.AD_Table_ID, f.Record_ID "); 
		int count=0;
		PreparedStatement pstmt = DB.prepareStatement (sql.toString(),ResultSet.TYPE_SCROLL_INSENSITIVE,  
		        ResultSet.CONCUR_UPDATABLE, get_TrxName());
		ResultSet rs = null;
		try {				
		  rs = pstmt.executeQuery();
		  //iAccumDepAcct=iDepAcct=0;
		  while (rs.next()){
			  iChargeID = rs.getInt("C_Charge_ID");
			  //if (iChargeID>0) continue;
			  iTableID = rs.getInt("AD_Table_ID");
			  iRecordID = rs.getInt("Record_ID");
			  iLineID = rs.getInt("Line_ID");
			  iCounter = rs.getInt("Counter");
			  iContractID = rs.getInt("CMS_Contract_ID");
			  iAID = rs.getInt("AID");
			  iAID2 = rs.getInt("AID2");
			  iAssetID = rs.getInt("A_Asset_ID");
			  iProductID = rs.getInt("M_Product_ID");
			  BigDecimal amtacctdr = rs.getBigDecimal("AmtAcctDr");
//			  BigDecimal amtacctcr = rs.getBigDecimal("AmtAcctCr");
			  int iBPID = rs.getInt("C_BPartner_ID");
				
				 if ((iTableID>0)&&(iRecordID>0)) {
					 switch (iTableID) {
					 	case 224: // Journal
					 		MJournalLine jl = new MJournalLine(getCtx(), iLineID, m_trxName);
					 		iChargeID = jl.getC_Charge_ID();
					 		if (iChargeID==0) {
						 		if ((iAID==1005337)&&(iAID2==1005507)) iChargeID=1000082;
						 		if ((iAID==1005337)&&(iAID2==1005458)) iChargeID=1000070;
						 		if ((iAID==1005337)&&(iAID2==1005447)) iChargeID=1000069;
						 		if ((iAID==1005337)&&(iAID2==1005485)) iChargeID=1000052;
						 		if ((iAID==1005337)&&(iAID2==1000211)) iChargeID=1000048;
						 		if ((iAID==1005337)&&(iAID2==1005479)) iChargeID=1000051;
						 		if ((iAID==1005562)&&(iAID2==1000283)) iChargeID=1000104;
					 		};
					 		if (iChargeID==0) continue;
					 		break;
					 	case 318:	//Invoice
					 		MInvoiceLine il = new MInvoiceLine(getCtx(), iLineID, m_trxName);
					 		MInvoice invoice = new MInvoice(getCtx(), iRecordID, m_trxName);
					 		iContractID = invoice.getCMS_Contract_ID();
					 		iAssetID = il.getA_Asset_ID();
					 		iProductID = il.getM_Product_ID();
					 		iChargeID = il.getC_Charge_ID();
					 		if (iChargeID==0) {
					 			if (il.getA_Asset_ID()!=0) iChargeID=1000172; 
					 			else continue;
					 		}
					 		break;
					 	case 319:	//Shipment/Receipt
					 		MInOutLine iol = new MInOutLine(getCtx(), iLineID, m_trxName);
					 		iChargeID = iol.getC_Charge_ID();
					 		if (iChargeID==0) continue;
					 		break;
					 	case 321:	//Phys.Inventory
					 		MInventoryLine invl = new MInventoryLine(getCtx(), iLineID, m_trxName);
					 		iChargeID = invl.getC_Charge_ID();
					 		if (iChargeID==0) continue;
					 		break;
					 	case 323:	//Inventory Move
					 		MMovement mv = new MMovement(getCtx(), iRecordID, m_trxName);
					 		if (mv!=null) {
					 			iChargeID = mv.getC_Charge_ID();
					 		}	
					 		if (iChargeID==0) continue;
					 		break;
					 	case 335:	//Payment
					 		MPayment pay = new MPayment(getCtx(), iRecordID, m_trxName);
					 		iContractID = pay.getCMS_Contract_ID();
					 		iChargeID = pay.getC_Charge_ID();
					 		if (iChargeID==0) continue;
					 		break;
					 	case 392:	//Bank Statement
					 		MBankStatementLine bsl = new MBankStatementLine(getCtx(), iLineID, m_trxName); 
					 		iChargeID = bsl.getC_Charge_ID();
					 		if (iChargeID==0) continue;
					 		break;
					 	case 1000066:	//hrm_bonus
					 		if ((iAID==1005337)&&(iAID2==1000211)) iChargeID=1000049;
					 		break;
//					 		Mhrmbonus  hbl = new Mhrmbonus(getCtx(), iLineID, m_trxName);
//					 		iChargeID = hbl.getC_Charge_ID();
//					 		if (iChargeID==0) continue;
					 	case 1000065:	//hrm_vacation
					 		if ((iAID==1005337)&&(iAID2==1005479)) iChargeID=1000051;
					 		if ((iAID==1005337)&&(iAID2==1005485)) iChargeID=1000052;
					 		if ((iAID==1005337)&&(iAID2==1005507)) iChargeID=1000082;
					 		if ((iAID==1005337)&&(iAID2==1000211)) iChargeID=1000048;
					 		//if (iChargeID==0) {
					 			Mhrmvacation hrv = new Mhrmvacation(getCtx(), iRecordID, m_trxName);
					 			Mhrmvacationline[] hrvl = hrv.getLinesVacation();
					 			for(int i = 0; i < hrvl.length; i++ ){
					 				Mhrmvacationline line = hrvl[i];
					 				Integer bp =  line.getC_BPartner_ID();
//					 				BigDecimal amountCharge = line.gethrm_total();
//					 				BigDecimal amountCNalog = line.gethrm_CNalog();
//					 				BigDecimal amountCOtch = line.gethrm_COtch();
//					 				BigDecimal amountIPN = line.gethrm_IPN();
//					 				BigDecimal amountOPV = line.gethrm_OPV();
					 				BigDecimal amountMaterialaid = line.gethrm_materialaid();
					 				if (iBPID==bp) {
					 					if (amtacctdr.equals(amountMaterialaid)) iChargeID=1000050;
					 				}
					 			}	
					 		if (iChargeID==0) continue;
					 		break;
					 	case 1000044:	//hrm_payment
					 		//if ((iAID==1005337)&&(iAID2==1000211)) iChargeID=1000048;
					 		//if (iChargeID==0) continue;
					 		//break;
					 	case 1000125: 	//hrm_checkoff
					 	case 1000128:	//hrm_materialaid
					 	case 1000173:	//hrm_review
					 	case 1000180:	//hrm_intercheckoff
					 	case 1000193:	//hrm_loan
					 		if ((iAID==1005337)&&(iAID2==1005479)) iChargeID=1000051;
					 		if ((iAID==1005337)&&(iAID2==1005485)) iChargeID=1000052;
					 		if ((iAID==1005337)&&(iAID2==1000211)) iChargeID=1000048;
					 		if ((iAID==1005337)&&(iAID2==1005507)) iChargeID=1000082;
					 		if ((iAID==1005331)&&(iAID2==1000211)) iChargeID=1000048;
					 		break;
					 	case 1000205:	//Asset Transaction
					 		if ((iAID==1005337)&&(iAID2==1005458)) iChargeID=1000070;
					 		if ((iAID==1005337)&&(iAID2==1005447)) iChargeID=1000069;
					 		if ((iAID==1000313)&&(iAID2==1005446)) iChargeID=1000089;
//					 		MAssetTransactionLine  hvl = new MAssetTransactionLine(getCtx(), iLineID, m_trxName);
//					 		iChargeID = hvl.getC_Charge_ID();
					 		if (iChargeID==0) continue;
					 		break;
						 
					 }
				 }
				 if (iChargeID > 0) {
					 /*rs.updateInt("C_Charge_ID", iChargeID);
					 rs.updateRow();*/
					 sql.setLength(0);
					 sql.append("UPDATE Fact_Acct SET C_Charge_ID="+iChargeID);
					 if (iContractID>0) sql.append(" , CMS_Contract_ID="+iContractID);
					 if (iAssetID>0) sql.append(" , A_Asset_ID="+iAssetID);
					 if (iProductID>0) sql.append(" , M_Product_ID="+iProductID);
					 sql.append(" WHERE AD_Table_ID="+iTableID
								+" AND Record_ID="+iRecordID
								+" AND Counter="+iCounter
								+" AND Line_ID ");
					 if (iLineID==0) sql.append(" IS NULL ");
					 else sql.append("= "+iLineID);
					int executeUpdate = DB.executeUpdate(sql.toString(),m_trxName);
					if (executeUpdate>0) count+=executeUpdate;
				 }	
		  }
		} catch (Exception e) {
			log.log(Level.SEVERE, "Error: " + e);
		} finally {
			DB.close(rs, pstmt);
		    rs = null; pstmt = null;
		}
		
		 sql.setLength(0);
		 sql.append("UPDATE adempiere.fact_acct as f1"
				 +" SET A_Asset_ID = c.A_Asset_ID, "
				 +" C_Charge_ID=1000213"
				 +" FROM adempiere.fact_acct as f " 
				 +" INNER JOIN "
				 +" adempiere.c_invoiceline as c "
				 +" ON c_invoiceline_id=f.line_id"
				 +"	where  f1.ad_table_id = 318 "
				 +" and f1.line_id>0 "
				 +" and f1.fact_acct_id=f.fact_acct_id "
				 +" and f1.account_id=1005446"
				 +" and c.a_asset_id>0");
		DB.executeUpdate(sql.toString(),m_trxName);

		return "@OK@"+count;
	} 

}
